package com.muy.redis.view.window.redis.tree;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import com.muy.redis.common.tree.MTTreeCell;
import com.muy.redis.common.tree.TreePanelMark;
import com.muy.redis.utils.GuiUtils;
import com.muy.redis.utils.MrRedisConnectionUtils;
import com.muy.redis.utils.ThreadPoolManager;
import com.muy.redis.view.window.redis.bean.MrRedisDb;
import com.muy.redis.view.window.redis.editor.KeyValueDisplayFileSystem;
import com.muy.redis.view.window.redis.editor.KeyValueDisplayVirtualFile;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 * @Author jiyanghuang
 * @Date 2022/8/5 00:07
 */
public class MTTreeCellMrRedisDb implements MTTreeCell {

    private Project project;

    private MrRedisDb mrRedisDb;

    public MTTreeCellMrRedisDb(Project project, MrRedisDb mrRedisDb) {
        this.project = project;
        this.mrRedisDb = mrRedisDb;
    }

    @Override
    public String cellShow() {
        return mrRedisDb.toString();
    }

    @Override
    public Icon iconSelected() {
        return GuiUtils.DB;
    }

    @Override
    public Icon iconUnselected() {
        return GuiUtils.DB;
    }

    @Override
    public void doubleClick(JTree tree, DefaultMutableTreeNode mutableTreeNode, TreePanelMark treePanelMark) {
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) mutableTreeNode.getParent();
        MTTreeCellMrRedisTopDb mtTreeCellMrRedisTopDb = (MTTreeCellMrRedisTopDb) parent.getUserObject();
        ReadAction.nonBlocking(() -> {
            try {
                String connectionId = mrRedisDb.getConnectionId();
                KeyValueDisplayVirtualFile keyValueDisplayVirtualFile = new KeyValueDisplayVirtualFile(mtTreeCellMrRedisTopDb.getMrRedisConnectionParam() + "-DB" + mrRedisDb.getIndex(),
                        project, mtTreeCellMrRedisTopDb.getMrRedisConnectionParam(), mrRedisDb, MrRedisConnectionUtils.findRedisPoolManager(mtTreeCellMrRedisTopDb.getMrRedisConnectionParam()));
                ApplicationManager.getApplication().invokeLater(() -> {
                    KeyValueDisplayFileSystem.getInstance(project).openEditor(keyValueDisplayVirtualFile);
                    MrRedisConnectionUtils.addEditorToMap(connectionId, keyValueDisplayVirtualFile);
                });
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {

            }
            return null;
        }).submit(ThreadPoolManager.getExecutor());
    }
}
